<template>
  <div class="inventory-review-container">
    <!-- 基础信息部分 -->
    <div class="basic-info-section">
      <h3 class="section-title">基础信息</h3>
      <div class="form-grid">
        <div class="form-left">
          <div class="form-item">
            <label class="required">盘点单号</label>
            <div class="order-number-input">
              <input 
                type="text" 
                v-model="basicInfo.orderNumber" 
                :placeholder="isLoading ? '正在获取...' : '自动获取系统编号'" 
                readonly 
              />
              <span v-if="isLoading" class="loading-spinner">⏳</span>
              <button 
                v-if="!isLoading && basicInfo.orderNumber" 
                class="refresh-btn" 
                @click="refreshOrderNumber"
                title="重新获取盘点单号"
              >
                🔄
              </button>
            </div>
          </div>
          <div class="form-item">
            <label class="required">盘点开始时间</label>
            <div class="datetime-input">
              <input 
                type="text" 
                v-model="basicInfo.startTime" 
                placeholder="请选择" 
                required 
                @click="openDatePicker('startTime')"
                readonly
              />
              <i class="calendar-icon" @click="openDatePicker('startTime')">
                <svg width="16" height="16" viewBox="0 0 24 24" fill="currentColor">
                  <path d="M19 3h-1V1h-2v2H8V1H6v2H5c-1.11 0-1.99.9-1.99 2L3 19c0 1.1.89 2 2 2h14c1.1 0 2-.9 2-2V5c0-1.1-.9-2-2-2zm0 16H5V8h14v11zM7 10h5v5H7z"/>
                </svg>
              </i>
            </div>
          </div>
          <div class="form-item">
            <label class="required">仓库名称</label>
            <div class="select-with-button">
              <select v-model="basicInfo.warehouse" required>
                <option value="">请选择</option>
                <option v-for="warehouse in warehouses" :key="warehouse.id" :value="warehouse.id">
                  {{ warehouse.name }}
                </option>
              </select>
              
            </div>
          </div>
        </div>
        <div class="form-right">
          <div class="form-item">
            <label>盘点类型</label>
            <select v-model="basicInfo.inventoryType">
              <option value="">请选择</option>
              <option value="full">全面盘点</option>
              <option value="partial">部分盘点</option>
              <option value="cycle">循环盘点</option>
            </select>
          </div>
          <div class="form-item">
            <label class="required">盘点结束时间</label>
            <div class="datetime-input">
              <input 
                type="text" 
                v-model="basicInfo.endTime" 
                placeholder="请选择" 
                required 
                @click="openDatePicker('endTime')"
                readonly
              />
              <i class="calendar-icon" @click="openDatePicker('endTime')">
                <svg width="16" height="16" viewBox="0 0 24 24" fill="currentColor">
                  <path d="M19 3h-1V1h-2v2H8V1H6v2H5c-1.11 0-1.99.9-1.99 2L3 19c0 1.1.89 2 2 2h14c1.1 0 2-.9 2-2V5c0-1.1-.9-2-2-2zm0 16H5V8h14v11zM7 10h5v5H7z"/>
                </svg>
              </i>
            </div>
          </div>
          
        </div>
      </div>
      <!-- 备注部分 -->
      <div class="remarks-section">
        <div class="form-item">
          <label>备注</label>
          <textarea v-model="basicInfo.remarks" placeholder="请输入"></textarea>
        </div>
      </div>
    </div>

    <!-- 盘点明细部分 -->
    <div class="inventory-details-section">
      <h3 class="section-title">盘点明细</h3>
      
      <!-- 操作按钮 -->
      <div class="action-buttons">
        <button class="btn btn-primary" @click="addInventoryItem">添加</button>
        <!-- <button class="btn btn-secondary" @click="removeSelectedItems">移除</button>
        <button class="btn btn-secondary" @click="importInventoryData">导入</button> -->
        
        <!-- 警告信息 -->
        <div class="warnings" v-if="showWarnings">
          <!-- <div class="warning-item" v-if="!basicInfo.warehouse">
            <span class="warning-icon">⚠️</span>
            <span>请选择仓库!</span>
          </div> -->
          <div class="warning-item" v-if="inventoryItems.length === 0">
            <span class="warning-icon">⚠️</span>
            <span>请选择货品!</span>
          </div>
        </div>
      </div>

      <!-- 盘点明细表格 -->
      <div class="table-container">
        <table class="inventory-table">
          <thead>
            <tr>
              <th>
                <input type="checkbox" v-model="selectAll" @change="toggleSelectAll" />
              </th>
              <th>序号</th>
              <th>货品名称</th>
              <th>货品编号</th>
              <th>规格型号</th>
              <th>单位</th>
              <th>货品类型</th>
              <th>账面库存</th>
              <th>账面金额</th>
              <th>盘点库位</th>
              <th>盘点数量 <span class="required">*</span></th>
              <th>盈亏数量</th>
              <th>盘点状态</th>
              <th>操作</th>
            </tr>
          </thead>
          <tbody>
            <tr v-for="(item, index) in inventoryItems" :key="item.id">
              <td>
                <input type="checkbox" v-model="item.selected" @change="updateSelectAll" />
              </td>
              <td>{{ index + 1 }}</td>
              <td>{{ item.goodsName }}</td>
              <td>{{ item.goodsNumber }}</td>
              <td>{{ item.specification }}</td>
              <td>{{ item.unit }}</td>
              <td>{{ item.goodsType }}</td>
              <td>{{ item.bookInventory }}</td>
              <td>{{ item.bookAmount }}</td>
              <td>
                <select v-model="item.inventoryLocation">
                  <option value="">请选择</option>
                  <option v-for="location in inventoryLocations" :key="location.id" :value="location.id">
                    {{ location.name }}
                  </option>
                </select>
              </td>
              <td>
                <div class="quantity-input">
                  <input 
                    type="text" 
                    v-model="item.inventoryQuantity" 
                    @input="calculateProfitLoss(index)"
                    required 
                  />
                  <button class="quantity-detail-btn" @click="openQuantityDetail(index)">...</button>
                </div>
              </td>
              <td>{{ item.profitLossQuantity }}</td>
              <td>
                <span :class="getStatusClass(item.inventoryStatus)">
                  {{ getStatusText(item.inventoryStatus) }}
                </span>
              </td>
              <td>
                <button class="btn btn-remove" @click="removeItem(index)">移除</button>
              </td>
            </tr>
          </tbody>
        </table>
      </div>
    </div>

    <!-- 自定义日期选择器弹窗 -->
    <div class="modal" v-if="showDatePicker" @click="closeDatePicker">
      <div class="date-picker-modal" @click.stop>
        <div class="date-picker-header">
          <button class="nav-btn" @click="previousYear">«</button>
          <button class="nav-btn" @click="previousMonth">‹</button>
          <span class="current-month">{{ currentDate.getFullYear() }}-{{ String(currentDate.getMonth() + 1).padStart(2, '0') }}</span>
          <button class="nav-btn" @click="nextMonth">›</button>
          <button class="nav-btn" @click="nextYear">»</button>
        </div>
        
        <div class="date-picker-weekdays">
          <div class="weekday">日</div>
          <div class="weekday">一</div>
          <div class="weekday">二</div>
          <div class="weekday">三</div>
          <div class="weekday">四</div>
          <div class="weekday">五</div>
          <div class="weekday">六</div>
        </div>
        
        <div class="date-picker-grid">
          <div 
            v-for="day in getCalendarDays()" 
            :key="day.date.getTime()"
            class="date-cell"
            :class="{
              'other-month': !day.isCurrentMonth,
              'selected': selectedDate.toDateString() === day.date.toDateString(),
              'today': new Date().toDateString() === day.date.toDateString()
            }"
            @click="selectDate(day.date)"
          >
            {{ day.date.getDate() }}
          </div>
        </div>
      </div>
    </div>

    <!-- 数量详情弹窗 -->
    <div class="modal" v-if="showQuantityModal" @click="closeQuantityModal">
      <div class="modal-content" @click.stop>
        <h4>数量详情</h4>
        <div class="quantity-detail-form">
          <div class="quantity-row">
            <label>箱数:</label>
            <input type="number" v-model="quantityDetail.boxes" @input="updateQuantityDetail" />
          </div>
          <div class="quantity-row">
            <label>瓶数:</label>
            <input type="number" v-model="quantityDetail.bottles" @input="updateQuantityDetail" />
          </div>
        </div>
        <div class="modal-actions">
          <button class="btn btn-primary" @click="confirmQuantityDetail">确定</button>
          <button class="btn btn-secondary" @click="closeQuantityModal">取消</button>
        </div>
      </div>
    </div>

    <!-- 底部操作按钮 -->
    <div class="bottom-actions">
      <button class="btn btn-primary" @click="saveInventoryReview">保存</button>
      <button class="btn btn-secondary" @click="cancelOperation">取消</button>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed, onMounted } from 'vue'

// 基础信息
const basicInfo = reactive({
  orderNumber: '',
  startTime: '',
  endTime: '',
  warehouse: '',
  inventoryType: '',
  handler: '',
  remarks: ''
})

// 从后台获取盘点单号
const getOrderNumberFromBackend = async () => {
  isLoading.value = true
  try {
    // 这里调用后台API获取盘点单号
    // const response = await axios.get('/api/inventory/generate-order-number')
    // basicInfo.orderNumber = response.data.orderNumber
    
    // 模拟API调用
    await new Promise(resolve => setTimeout(resolve, 500))
    const mockOrderNumber = 'INV' + Date.now()
    basicInfo.orderNumber = mockOrderNumber
    
    console.log('获取盘点单号成功:', basicInfo.orderNumber)
  } catch (error) {
    console.error('获取盘点单号失败:', error)
    basicInfo.orderNumber = '获取失败'
  } finally {
    isLoading.value = false
  }
}



// 仓库列表
const warehouses = ref([
  { id: 'wh1', name: '主仓库' },
  { id: 'wh2', name: '分仓库A' },
  { id: 'wh3', name: '分仓库B' }
])

// 经办人列表
const handlers = ref([
  { id: 'h1', name: '张三' },
  { id: 'h2', name: '李四' },
  { id: 'h3', name: '王五' }
])

// 盘点库位列表
const inventoryLocations = ref([
  { id: 'loc1', name: 'A区-01' },
  { id: 'loc2', name: 'A区-02' },
  { id: 'loc3', name: 'B区-01' },
  { id: 'loc4', name: 'B区-02' }
])

// 盘点明细数据
const inventoryItems = ref([
  {
    id: 1,
    selected: false,
    goodsName: '货品一',
    goodsNumber: 'HPBH00002',
    specification: '600ml',
    unit: '包',
    goodsType: '饮品',
    bookInventory: '2',
    bookAmount: '600.00',
    inventoryLocation: '',
    inventoryQuantity: '1',
    profitLossQuantity: '-1',
    inventoryStatus: 'deficit'
  },
  {
    id: 2,
    selected: false,
    goodsName: '货品二',
    goodsNumber: 'HPBH00003',
    specification: '红',
    unit: '袋',
    goodsType: '饮品',
    bookInventory: '2',
    bookAmount: '600.00',
    inventoryLocation: '',
    inventoryQuantity: '2',
    profitLossQuantity: '0',
    inventoryStatus: 'normal'
  },
  {
    id: 3,
    selected: false,
    goodsName: '货品三',
    goodsNumber: 'HPBH00004',
    specification: '90*20',
    unit: '瓶',
    goodsType: '饮品',
    bookInventory: '2',
    bookAmount: '600.00',
    inventoryLocation: '',
    inventoryQuantity: '3',
    profitLossQuantity: '1',
    inventoryStatus: 'surplus'
  },
  {
    id: 4,
    selected: false,
    goodsName: '货品四',
    goodsNumber: 'HPBH00005',
    specification: '蓝',
    unit: '瓶/箱(6瓶)',
    goodsType: '饮品',
    bookInventory: '5瓶16箱',
    bookAmount: '600.00',
    inventoryLocation: '',
    inventoryQuantity: '17箱6瓶',
    profitLossQuantity: '1箱1瓶',
    inventoryStatus: 'surplus'
  },
  {
    id: 5,
    selected: false,
    goodsName: '货品五',
    goodsNumber: 'HPBH00006',
    specification: '1kg',
    unit: '瓶/箱(6瓶)',
    goodsType: '饮品',
    bookInventory: '5瓶16箱',
    bookAmount: '600.00',
    inventoryLocation: '',
    inventoryQuantity: '17箱6瓶',
    profitLossQuantity: '1箱1瓶',
    inventoryStatus: 'surplus'
  }
])

// 全选状态
const selectAll = ref(false)

// 警告显示状态
const showWarnings = computed(() => {
  return !basicInfo.warehouse || inventoryItems.value.length === 0
})

// 加载状态
const isLoading = ref(false)

// 日期选择器状态
const showDatePicker = ref(false)
const currentDateField = ref<'startTime' | 'endTime' | null>(null)
const currentDate = ref(new Date())
const selectedDate = ref(new Date())

// 数量详情弹窗
const showQuantityModal = ref(false)
const currentQuantityIndex = ref(-1)
const quantityDetail = reactive({
  boxes: 0,
  bottles: 0
})

// 计算盈亏数量
const calculateProfitLoss = (index: number) => {
  const item = inventoryItems.value[index]
  
  // 解析账面库存
  let bookQty = 0
  if (item.bookInventory.includes('箱') && item.bookInventory.includes('瓶')) {
    const boxMatch = item.bookInventory.match(/(\d+)箱/)
    const bottleMatch = item.bookInventory.match(/(\d+)瓶/)
    const boxes = boxMatch ? parseInt(boxMatch[1]) : 0
    const bottles = bottleMatch ? parseInt(bottleMatch[1]) : 0
    bookQty = boxes * 6 + bottles // 假设1箱=6瓶
  } else {
    bookQty = parseFloat(item.bookInventory) || 0
  }
  
  // 解析盘点数量
  let inventoryQty = 0
  if (item.inventoryQuantity.includes('箱') && item.inventoryQuantity.includes('瓶')) {
    const boxMatch = item.inventoryQuantity.match(/(\d+)箱/)
    const bottleMatch = item.inventoryQuantity.match(/(\d+)瓶/)
    const boxes = boxMatch ? parseInt(boxMatch[1]) : 0
    const bottles = bottleMatch ? parseInt(bottleMatch[1]) : 0
    inventoryQty = boxes * 6 + bottles // 假设1箱=6瓶
  } else {
    inventoryQty = parseFloat(item.inventoryQuantity) || 0
  }
  
  const difference = inventoryQty - bookQty
  
  // 格式化盈亏数量显示
  if (item.unit.includes('箱')) {
    const diffBoxes = Math.floor(difference / 6)
    const diffBottles = difference % 6
    if (diffBoxes > 0 && diffBottles > 0) {
      item.profitLossQuantity = `${diffBoxes}箱${diffBottles}瓶`
    } else if (diffBoxes > 0) {
      item.profitLossQuantity = `${diffBoxes}箱`
    } else if (diffBottles > 0) {
      item.profitLossQuantity = `${diffBottles}瓶`
    } else {
      item.profitLossQuantity = '0'
    }
  } else {
    item.profitLossQuantity = difference.toString()
  }
  
  // 更新状态
  if (difference > 0) {
    item.inventoryStatus = 'surplus'
  } else if (difference < 0) {
    item.inventoryStatus = 'deficit'
  } else {
    item.inventoryStatus = 'normal'
  }
}

// 获取状态样式类
const getStatusClass = (status: string) => {
  switch (status) {
    case 'surplus':
      return 'status-surplus'
    case 'deficit':
      return 'status-deficit'
    case 'normal':
      return 'status-normal'
    default:
      return ''
  }
}

// 获取状态文本
const getStatusText = (status: string) => {
  switch (status) {
    case 'surplus':
      return '盘盈'
    case 'deficit':
      return '盘亏'
    case 'normal':
      return '无盈亏'
    default:
      return ''
  }
}

// 添加盘点项目
const addInventoryItem = () => {
  const newItem = {
    id: Date.now(),
    selected: false,
    goodsName: '新货品',
    goodsNumber: 'HPBH' + String(Date.now()).slice(-5),
    specification: '',
    unit: '',
    goodsType: '饮品',
    bookInventory: '0',
    bookAmount: '0.00',
    inventoryLocation: '',
    inventoryQuantity: '0',
    profitLossQuantity: '0',
    inventoryStatus: 'normal'
  }
  inventoryItems.value.push(newItem)
}

// 移除选中项目
const removeSelectedItems = () => {
  inventoryItems.value = inventoryItems.value.filter(item => !item.selected)
  updateSelectAll()
}

// 移除单个项目
const removeItem = (index: number) => {
  inventoryItems.value.splice(index, 1)
  updateSelectAll()
}

// 导入盘点数据
const importInventoryData = () => {
  // 这里可以实现文件上传或数据导入功能
  alert('导入功能待实现')
}

// 全选/取消全选
const toggleSelectAll = () => {
  inventoryItems.value.forEach(item => {
    item.selected = selectAll.value
  })
}

// 更新全选状态
const updateSelectAll = () => {
  selectAll.value = inventoryItems.value.length > 0 && 
    inventoryItems.value.every(item => item.selected)
}

// 打开数量详情
const openQuantityDetail = (index: number) => {
  currentQuantityIndex.value = index
  const item = inventoryItems.value[index]
  // 解析现有数量
  const quantity = item.inventoryQuantity
  if (quantity.includes('箱') && quantity.includes('瓶')) {
    const boxMatch = quantity.match(/(\d+)箱/)
    const bottleMatch = quantity.match(/(\d+)瓶/)
    quantityDetail.boxes = boxMatch ? parseInt(boxMatch[1]) : 0
    quantityDetail.bottles = bottleMatch ? parseInt(bottleMatch[1]) : 0
  } else {
    quantityDetail.boxes = 0
    quantityDetail.bottles = 0
  }
  showQuantityModal.value = true
}

// 更新数量详情
const updateQuantityDetail = () => {
  // 实时更新显示
}

// 确认数量详情
const confirmQuantityDetail = () => {
  const item = inventoryItems.value[currentQuantityIndex.value]
  item.inventoryQuantity = `${quantityDetail.boxes}箱${quantityDetail.bottles}瓶`
  calculateProfitLoss(currentQuantityIndex.value)
  closeQuantityModal()
}

// 关闭数量详情弹窗
const closeQuantityModal = () => {
  showQuantityModal.value = false
  currentQuantityIndex.value = -1
}

// 仓库设置
const openWarehouseSettings = () => {
  alert('仓库设置功能待实现')
}

// 经办人选择
const openHandlerSelection = () => {
  alert('经办人选择功能待实现')
}

// 打开日期时间选择器
const openDateTimePicker = (field: 'startTime' | 'endTime') => {
  const input = document.createElement('input')
  input.type = 'datetime-local'
  input.style.position = 'absolute'
  input.style.left = '-9999px'
  document.body.appendChild(input)
  
  // 设置默认值为当前时间
  const now = new Date()
  const year = now.getFullYear()
  const month = String(now.getMonth() + 1).padStart(2, '0')
  const day = String(now.getDate()).padStart(2, '0')
  const hours = String(now.getHours()).padStart(2, '0')
  const minutes = String(now.getMinutes()).padStart(2, '0')
  input.value = `${year}-${month}-${day}T${hours}:${minutes}`
  
  input.addEventListener('change', (e) => {
    const target = e.target as HTMLInputElement
    if (target.value) {
      const date = new Date(target.value)
      const formattedDate = `${date.getFullYear()}/${String(date.getMonth() + 1).padStart(2, '0')}/${String(date.getDate()).padStart(2, '0')} ${String(date.getHours()).padStart(2, '0')}:${String(date.getMinutes()).padStart(2, '0')}`
      basicInfo[field] = formattedDate
      
      // 如果设置了开始时间，自动设置结束时间为开始时间+1小时
      if (field === 'startTime' && !basicInfo.endTime) {
        const endDate = new Date(date.getTime() + 60 * 60 * 1000) // 加1小时
        const endFormattedDate = `${endDate.getFullYear()}/${String(endDate.getMonth() + 1).padStart(2, '0')}/${String(endDate.getDate()).padStart(2, '0')} ${String(endDate.getHours()).padStart(2, '0')}:${String(endDate.getMinutes()).padStart(2, '0')}`
        basicInfo.endTime = endFormattedDate
      }
    }
    document.body.removeChild(input)
  })
  
  input.addEventListener('blur', () => {
    if (document.body.contains(input)) {
      document.body.removeChild(input)
    }
  })
  
  input.click()
}

// 表单验证
const validateForm = () => {
  const errors = []
  
  // 验证基础信息
  if (!basicInfo.orderNumber) {
    errors.push('请获取盘点单号')
  }
  if (!basicInfo.startTime) {
    errors.push('请选择盘点开始时间')
  }
  if (!basicInfo.endTime) {
    errors.push('请选择盘点结束时间')
  }
  if (!basicInfo.warehouse) {
    errors.push('请选择仓库名称')
  }
  
  // 验证时间逻辑
  if (basicInfo.startTime && basicInfo.endTime) {
    const startTime = new Date(basicInfo.startTime.replace(/\//g, '-'))
    const endTime = new Date(basicInfo.endTime.replace(/\//g, '-'))
    if (endTime <= startTime) {
      errors.push('盘点结束时间必须晚于开始时间')
    }
  }
  
  // 验证盘点明细
  if (inventoryItems.value.length === 0) {
    errors.push('请添加盘点明细')
  } else {
    const invalidItems = inventoryItems.value.filter(item => 
      !item.inventoryQuantity || item.inventoryQuantity === '0'
    )
    if (invalidItems.length > 0) {
      errors.push('请填写所有盘点数量')
    }
  }
  
  return errors
}

// 保存盘点单
const saveInventoryReview = () => {
  const errors = validateForm()
  
  if (errors.length > 0) {
    alert('请检查以下问题：\n' + errors.join('\n'))
    return
  }
  
  // 这里可以调用API保存数据
  const saveData = {
    basicInfo: { ...basicInfo },
    inventoryItems: inventoryItems.value.map(item => ({ ...item }))
  }
  
  console.log('保存盘点单:', saveData)
  
  // 模拟API调用
  setTimeout(() => {
    alert('保存成功！')
    // 这里可以跳转到列表页面或重置表单
  }, 1000)
}

// 打开日期选择器
const openDatePicker = (field: 'startTime' | 'endTime') => {
  currentDateField.value = field
  showDatePicker.value = true
  
  // 如果已有选择的时间，解析并设置为当前显示日期
  const timeValue = basicInfo[field]
  if (timeValue) {
    try {
      const date = new Date(timeValue.replace(/\//g, '-'))
      currentDate.value = new Date(date.getFullYear(), date.getMonth(), 1)
      selectedDate.value = date
    } catch (error) {
      currentDate.value = new Date()
      selectedDate.value = new Date()
    }
  } else {
    currentDate.value = new Date()
    selectedDate.value = new Date()
  }
}

// 关闭日期选择器
const closeDatePicker = () => {
  showDatePicker.value = false
  currentDateField.value = null
}

// 选择日期
const selectDate = (date: Date) => {
  selectedDate.value = date
  const formatTime = (date: Date) => {
    const year = date.getFullYear()
    const month = String(date.getMonth() + 1).padStart(2, '0')
    const day = String(date.getDate()).padStart(2, '0')
    const hours = String(date.getHours()).padStart(2, '0')
    const minutes = String(date.getMinutes()).padStart(2, '0')
    return `${year}/${month}/${day} ${hours}:${minutes}`
  }
  
  if (currentDateField.value) {
    basicInfo[currentDateField.value] = formatTime(date)
    
    // 如果选择的是开始时间，自动更新结束时间
    if (currentDateField.value === 'startTime') {
      const endDate = new Date(date.getTime() + 60 * 60 * 1000) // 加1小时
      basicInfo.endTime = formatTime(endDate)
    }
  }
  
  closeDatePicker()
}

// 上个月
const previousMonth = () => {
  currentDate.value = new Date(currentDate.value.getFullYear(), currentDate.value.getMonth() - 1, 1)
}

// 下个月
const nextMonth = () => {
  currentDate.value = new Date(currentDate.value.getFullYear(), currentDate.value.getMonth() + 1, 1)
}

// 上一年
const previousYear = () => {
  currentDate.value = new Date(currentDate.value.getFullYear() - 1, currentDate.value.getMonth(), 1)
}

// 下一年
const nextYear = () => {
  currentDate.value = new Date(currentDate.value.getFullYear() + 1, currentDate.value.getMonth(), 1)
}

// 获取月份的天数
const getDaysInMonth = (year: number, month: number) => {
  return new Date(year, month + 1, 0).getDate()
}

// 获取月份第一天是星期几
const getFirstDayOfMonth = (year: number, month: number) => {
  return new Date(year, month, 1).getDay()
}

// 生成日历数据
const getCalendarDays = () => {
  const year = currentDate.value.getFullYear()
  const month = currentDate.value.getMonth()
  const daysInMonth = getDaysInMonth(year, month)
  const firstDay = getFirstDayOfMonth(year, month)
  
  const days = []
  
  // 添加上个月的日期
  const prevMonth = month === 0 ? 11 : month - 1
  const prevYear = month === 0 ? year - 1 : year
  const daysInPrevMonth = getDaysInMonth(prevYear, prevMonth)
  
  for (let i = firstDay - 1; i >= 0; i--) {
    days.push({
      date: new Date(prevYear, prevMonth, daysInPrevMonth - i),
      isCurrentMonth: false
    })
  }
  
  // 添加当前月的日期
  for (let day = 1; day <= daysInMonth; day++) {
    days.push({
      date: new Date(year, month, day),
      isCurrentMonth: true
    })
  }
  
  // 添加下个月的日期
  const nextMonth = month === 11 ? 0 : month + 1
  const nextYear = month === 11 ? year + 1 : year
  const remainingDays = 42 - days.length // 保持6行7列的格式
  
  for (let day = 1; day <= remainingDays; day++) {
    days.push({
      date: new Date(nextYear, nextMonth, day),
      isCurrentMonth: false
    })
  }
  
  return days
}

// 重新获取盘点单号
const refreshOrderNumber = async () => {
  if (isLoading.value) return
  await getOrderNumberFromBackend()
}

// 取消操作
const cancelOperation = () => {
  if (confirm('确定要取消吗？未保存的数据将丢失。')) {
    // 这里可以返回上一页或清空数据
    console.log('取消操作')
  }
}

// 自动设置默认时间
const setDefaultTimes = () => {
  const now = new Date()
  const startTime = new Date(now.getTime())
  const endTime = new Date(now.getTime() + 60 * 60 * 1000) // 当前时间+1小时
  
  // 格式化时间
  const formatTime = (date: Date) => {
    const year = date.getFullYear()
    const month = String(date.getMonth() + 1).padStart(2, '0')
    const day = String(date.getDate()).padStart(2, '0')
    const hours = String(date.getHours()).padStart(2, '0')
    const minutes = String(date.getMinutes()).padStart(2, '0')
    return `${year}/${month}/${day} ${hours}:${minutes}`
  }
  
  basicInfo.startTime = formatTime(startTime)
  basicInfo.endTime = formatTime(endTime)
}

// 验证时间格式并自动更新结束时间
const validateTimeFormat = (field: 'startTime' | 'endTime') => {
  const timeValue = basicInfo[field]
  if (!timeValue) return
  
  // 检查时间格式是否正确 (yyyy/mm/dd hh:mm)
  const timeRegex = /^\d{4}\/\d{2}\/\d{2} \d{2}:\d{2}$/
  if (!timeRegex.test(timeValue)) {
    // 如果格式不正确，可以在这里添加提示或自动格式化
    console.warn(`时间格式不正确: ${timeValue}`)
    return
  }
  
  // 如果修改的是开始时间，自动更新结束时间
  if (field === 'startTime') {
    try {
      const startDate = new Date(timeValue.replace(/\//g, '-'))
      const endDate = new Date(startDate.getTime() + 60 * 60 * 1000) // 加1小时
      
      const formatTime = (date: Date) => {
        const year = date.getFullYear()
        const month = String(date.getMonth() + 1).padStart(2, '0')
        const day = String(date.getDate()).padStart(2, '0')
        const hours = String(date.getHours()).padStart(2, '0')
        const minutes = String(date.getMinutes()).padStart(2, '0')
        return `${year}/${month}/${day} ${hours}:${minutes}`
      }
      
      basicInfo.endTime = formatTime(endDate)
    } catch (error) {
      console.error('时间解析错误:', error)
    }
  }
}

// 组件挂载时初始化
onMounted(async () => {
  // 初始化数据
  await getOrderNumberFromBackend()
  setDefaultTimes()
  updateSelectAll()
})
</script>

<style scoped>
.inventory-review-container {
  padding: 20px;
  background: #f5f5f5;
  min-height: 100vh;
}

.basic-info-section,
.inventory-details-section {
  background: white;
  border-radius: 8px;
  padding: 20px;
  margin-bottom: 20px;
  box-shadow: 0 2px 4px rgba(0,0,0,0.1);
}

.section-title {
  font-size: 18px;
  font-weight: bold;
  margin-bottom: 20px;
  color: #333;
  border-bottom: 2px solid #e0e0e0;
  padding-bottom: 10px;
}

.form-grid {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 30px;
  margin-bottom: 20px;
}

.form-item {
  margin-bottom: 15px;
}

.form-item label {
  display: block;
  margin-bottom: 5px;
  font-weight: 500;
  color: #333;
}

.form-item label.required::after {
  content: ' *';
  color: #ff4757;
}

.form-item input,
.form-item select,
.form-item textarea {
  width: 100%;
  padding: 8px 12px;
  border: 1px solid #ddd;
  border-radius: 4px;
  font-size: 14px;
}

.form-item textarea {
  height: 80px;
  resize: vertical;
}

.datetime-input {
  position: relative;
  display: flex;
  align-items: center;
}

.datetime-input input {
  padding-right: 35px;
  border: 2px solid #ddd;
  border-radius: 4px;
  transition: border-color 0.3s;
  background-color: #fff;
  cursor: pointer;
}

.datetime-input input:focus {
  border-color: #28a745;
  outline: none;
}

.datetime-input input:hover {
  border-color: #28a745;
}

.calendar-icon {
  position: absolute;
  right: 10px;
  top: 50%;
  transform: translateY(-50%);
  cursor: pointer;
  color: #4a90e2;
  transition: color 0.3s;
  display: flex;
  align-items: center;
  justify-content: center;
  width: 20px;
  height: 20px;
}

.calendar-icon:hover {
  color: #357abd;
}

.calendar-icon svg {
  width: 16px;
  height: 16px;
}

.remarks-section {
  margin-top: 20px;
  padding-top: 20px;
  border-top: 1px solid #e0e0e0;
}

.remarks-section .form-item {
  margin-bottom: 0;
}

.remarks-section textarea {
  height: 100px;
}

.order-number-input {
  position: relative;
  display: flex;
  align-items: center;
}

.order-number-input input {
  padding-right: 35px;
}

.refresh-btn {
  position: absolute;
  right: 10px;
  top: 50%;
  transform: translateY(-50%);
  background: none;
  border: none;
  cursor: pointer;
  font-size: 16px;
  padding: 4px;
  border-radius: 4px;
  transition: background-color 0.3s;
}

.refresh-btn:hover {
  background-color: #f0f0f0;
}

.loading-spinner {
  position: absolute;
  right: 10px;
  top: 50%;
  transform: translateY(-50%);
  font-size: 16px;
  animation: spin 1s linear infinite;
}

@keyframes spin {
  from { transform: translateY(-50%) rotate(0deg); }
  to { transform: translateY(-50%) rotate(360deg); }
}

.select-with-button {
  display: flex;
  gap: 8px;
}

.select-with-button select {
  flex: 1;
}

.settings-btn,
.more-btn {
  padding: 8px 12px;
  border: 1px solid #ddd;
  background: white;
  border-radius: 4px;
  cursor: pointer;
}

.settings-btn:hover,
.more-btn:hover {
  background: #f8f9fa;
}

.action-buttons {
  display: flex;
  align-items: center;
  gap: 15px;
  margin-bottom: 20px;
}

.btn {
  padding: 8px 16px;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-size: 14px;
  transition: all 0.3s;
}

.btn-primary {
  background: #28a745;
  color: white;
}

.btn-primary:hover {
  background: #218838;
}

.btn-secondary {
  background: white;
  color: #333;
  border: 1px solid #ddd;
}

.btn-secondary:hover {
  background: #f8f9fa;
}

.btn-remove {
  background: #dc3545;
  color: white;
  padding: 4px 8px;
  font-size: 12px;
}

.btn-remove:hover {
  background: #c82333;
}

.warnings {
  display: flex;
  gap: 15px;
}

.warning-item {
  display: flex;
  align-items: center;
  gap: 5px;
  color: #ff6b35;
  font-size: 14px;
}

.warning-icon {
  font-size: 16px;
}

.table-container {
  overflow-x: auto;
}

.inventory-table {
  width: 100%;
  border-collapse: collapse;
  font-size: 14px;
}

.inventory-table th,
.inventory-table td {
  padding: 12px 8px;
  text-align: left;
  border-bottom: 1px solid #e0e0e0;
}

.inventory-table th {
  background: #f8f9fa;
  font-weight: 600;
  color: #333;
}

.inventory-table th.required::after {
  content: ' *';
  color: #ff4757;
}

.quantity-input {
  display: flex;
  gap: 4px;
}

.quantity-input input {
  flex: 1;
  padding: 4px 8px;
  border: 1px solid #ddd;
  border-radius: 4px;
}

.quantity-detail-btn {
  padding: 4px 8px;
  border: 1px solid #ddd;
  background: white;
  border-radius: 4px;
  cursor: pointer;
}

.status-surplus {
  background: #28a745;
  color: white;
  padding: 4px 8px;
  border-radius: 4px;
  font-size: 12px;
}

.status-deficit {
  background: #dc3545;
  color: white;
  padding: 4px 8px;
  border-radius: 4px;
  font-size: 12px;
}

.status-normal {
  background: #007bff;
  color: white;
  padding: 4px 8px;
  border-radius: 4px;
  font-size: 12px;
}

/* 弹窗样式 */
.modal {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background: rgba(0,0,0,0.5);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 1000;
}

.modal-content {
  background: white;
  padding: 20px;
  border-radius: 8px;
  min-width: 300px;
}

/* 日期选择器样式 */
.date-picker-modal {
  background: white;
  border-radius: 8px;
  box-shadow: 0 4px 12px rgba(0,0,0,0.15);
  padding: 20px;
  min-width: 320px;
}

.date-picker-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 15px;
  padding: 0 10px;
}

.nav-btn {
  background: none;
  border: none;
  font-size: 18px;
  cursor: pointer;
  padding: 5px 8px;
  border-radius: 4px;
  transition: background-color 0.3s;
}

.nav-btn:hover {
  background-color: #f0f0f0;
}

.current-month {
  font-size: 16px;
  font-weight: 600;
  color: #333;
}

.date-picker-weekdays {
  display: grid;
  grid-template-columns: repeat(7, 1fr);
  gap: 1px;
  margin-bottom: 10px;
}

.weekday {
  text-align: center;
  padding: 8px 0;
  font-size: 14px;
  font-weight: 500;
  color: #666;
  background-color: #f8f9fa;
}

.date-picker-grid {
  display: grid;
  grid-template-columns: repeat(7, 1fr);
  gap: 1px;
}

.date-cell {
  text-align: center;
  padding: 10px 0;
  cursor: pointer;
  font-size: 14px;
  border-radius: 4px;
  transition: all 0.3s;
  user-select: none;
}

.date-cell:hover {
  background-color: #e3f2fd;
}

.date-cell.other-month {
  color: #ccc;
}

.date-cell.selected {
  background-color: #1976d2;
  color: white;
}

.date-cell.today {
  background-color: #e3f2fd;
  color: #1976d2;
  font-weight: 600;
}

.date-cell.today.selected {
  background-color: #1976d2;
  color: white;
}

.modal-content h4 {
  margin-bottom: 15px;
  color: #333;
}

.quantity-detail-form {
  margin-bottom: 20px;
}

.quantity-row {
  display: flex;
  align-items: center;
  margin-bottom: 10px;
}

.quantity-row label {
  width: 60px;
  margin-right: 10px;
}

.quantity-row input {
  flex: 1;
  padding: 8px;
  border: 1px solid #ddd;
  border-radius: 4px;
}

.modal-actions {
  display: flex;
  gap: 10px;
  justify-content: flex-end;
}

/* 底部操作按钮 */
.bottom-actions {
  background: white;
  border-radius: 8px;
  padding: 20px;
  text-align: center;
  box-shadow: 0 2px 4px rgba(0,0,0,0.1);
  margin-top: 20px;
}

.bottom-actions .btn {
  margin: 0 10px;
  min-width: 100px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .form-grid {
    grid-template-columns: 1fr;
  }
  
  .action-buttons {
    flex-direction: column;
    align-items: flex-start;
  }
  
  .warnings {
    flex-direction: column;
  }
  
  .bottom-actions .btn {
    margin: 5px;
  }
}
</style>



